import { forwardRef, useImperativeHandle, useMemo, useRef, useState } from 'react';

import { useRequest } from 'ahooks';
import { Button, Drawer, Form, FormProps, Input, Space, TreeSelect } from 'antd';
import { DataNode } from 'antd/es/tree';

import { store } from '@/store';

import { orgDeptInfoTreeList } from '@/services/base/bumenguanlibumenxiangguanjiekou';
import {
  manageNeedAdd,
  manageNeedGet,
  manageNeedUpdate
} from '@/services/bizApi/jingyingcaigouxuqiubiaojiekou';
import { findIdByName } from '@/utils';
import { ActionType, EditableProTable, ProColumns } from '@ant-design/pro-components';

import { BizObject } from './';

type DataSourceType = {
  key: React.Key;
  title?: string;
  readonly?: string;
  decs?: string;
  state?: string;
  created_at?: number;
  update_at?: number;
  children?: DataSourceType[];
};

type EditOpenBaseArgs = {
  /** 成功回调 */
  onSuccess?: () => void;
};

export type EditRef = {
  open: (
    arg:
      | (EditOpenBaseArgs & {
          type: 'add';
        })
      | (EditOpenBaseArgs & {
          type: 'edit';
          rowData: BizObject;
        })
      | (EditOpenBaseArgs & {
          type: 'detail';
          rowData: BizObject;
        })
  ) => void;
};

export type EditProps = {};

const Edit: React.ForwardRefRenderFunction<EditRef, EditProps> = (_, ref) => {
  const [form] = Form.useForm();
  const actionRef = useRef<ActionType>();
  // 弹窗开启状态
  const [open, setOpen] = useState(false);
  const [args, setArgs] = useState<ArgumentsType<EditRef['open']>[0]>();
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);
  const [dataSource, setDataSource] = useState<readonly DataSourceType[]>([]);
  const treeDict = useRef<Record<number, DataNode>>({});

  const tree = useRequest(async () => {
    treeDict.current = {};

    const res = await orgDeptInfoTreeList();

    const formatData = (data: BASE.OrgDeptInfoVo[]): DataNode[] => {
      const result: DataNode[] = [];

      data.forEach((item) => {
        const node: DataNode = {
          title: item.deptName,
          key: item.id!,
          // @ts-ignore
          value: item.id!,
          children: []
        };

        treeDict.current[item.id!] = node;

        if (item.child && item.child.length > 0) {
          node.children = formatData(item.child);
        }

        result.push(node);
      });

      return result;
    };

    return formatData(res.data || []);
  });

  const manageNeed = useRequest(
    async (id: string) => {
      const res = await manageNeedGet({ id });
      const data = res?.data;
      // 回填数据
      form.setFieldsValue({
        ...res?.data
      });
      setDataSource(
        (data?.detailEntityList?.map((item) => {
          return {
            ...item,
            key: item?.id
          };
        }) as unknown as DataSourceType[]) || []
      );
    },
    {
      manual: true
    }
  );

  const submit = useRequest(
    async ({ _type, ...values }) => {
      if (!dataSource?.length) {
        store.app?.message.info('请添加详情');
        return;
      }
      const query = {
        ...values,
        applyDeptName: findIdByName(tree?.data || [], values?.applyDeptId as unknown as string),
        detailEntityList: dataSource
      };

      if (args?.type === 'edit' && args.rowData) {
        query.id = args.rowData.id;
      }

      await (args?.type === 'edit' ? manageNeedUpdate(query) : manageNeedAdd(query));

      args?.onSuccess?.();
      setOpen(false);
      setDataSource([]);

      store.app?.message.success(args?.type === 'edit' ? '编辑成功' : '新增成功');
    },
    {
      manual: true
    }
  );

  useImperativeHandle(ref, () => {
    return {
      open: (arg) => {
        setArgs(arg);
        setOpen(true);

        setTimeout(() => {
          // 编辑回填数据
          if ((arg?.type === 'edit' || arg?.type === 'detail') && arg?.rowData) {
            // 回填数据
            manageNeed.run(arg?.rowData?.id as unknown as string);
          } else {
            form.resetFields();
          }
        });
      }
    };
  });

  const onFinish: FormProps['onFinish'] = async (values) => {
    return submit.runAsync(values);
  };

  const onCancel = () => {
    if (submit.loading) {
      store.app?.message.info('正在提交中，请稍后');

      return;
    }

    setOpen(false);
    setDataSource([]);
  };

  // 仅保存
  const onSave = () => {
    form.submit();
  };

  const columns: ProColumns<DataSourceType>[] = [
    {
      title: '名称',
      dataIndex: 'name',
      formItemProps: {
        rules: [{ required: true, message: '请输入名称' }]
      },
      align: 'center',
      width: 130
    },
    {
      title: '数量',
      dataIndex: 'number',
      valueType: 'digit',
      formItemProps: {
        rules: [{ required: true, message: '请输入数量' }]
      },
      align: 'center',
      width: 130
    },
    {
      title: '单价',
      dataIndex: 'money',
      valueType: 'digit',
      formItemProps: {
        rules: [{ required: true, message: '请输入单价' }]
      },
      align: 'center',
      width: 130
    },
    {
      title: '操作',
      valueType: 'option',
      fixed: 'right',
      width: 150,
      hidden: args?.type === 'detail',
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={() => {
            if (args?.type === 'detail') return;
            action?.startEditable?.(record.key);
          }}
        >
          编辑
        </a>,
        <a
          key="delete"
          onClick={() => {
            if (args?.type === 'detail') return;
            setDataSource(dataSource.filter((item) => item.key !== record.key));
          }}
        >
          删除
        </a>
      ]
    }
  ];

  const purchaseAmount = useMemo(() => {
    console.log('dataSource', dataSource);
    let num = 0;
    dataSource?.forEach((item: any) => {
      num += item?.number * item?.money;
    });
    form?.setFieldsValue({ purchaseAmount: num });
  }, [dataSource]);

  return (
    <Drawer
      title={
        {
          add: '新增',
          edit: '编辑',
          detail: '详情'
        }[args?.type as string]
      }
      extra={
        <>
          {args?.type !== 'detail' && (
            <Space>
              <Button
                type="primary"
                loading={submit.loading}
                disabled={submit.loading}
                onClick={onSave}
              >
                保存
              </Button>
              <Button onClick={onCancel} disabled={submit.loading}>
                取消
              </Button>
            </Space>
          )}
        </>
      }
      width="50%"
      open={open}
      onClose={onCancel}
    >
      <Form
        onFinish={onFinish}
        form={form}
        layout="horizontal"
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 14 }}
        disabled={args?.type === 'detail'}
        requiredMark={args?.type !== 'detail'}
        variant={args?.type === 'detail' ? 'borderless' : undefined}
      >
        <Form.Item
          label="申请部门"
          name="applyDeptId"
          rules={[
            {
              required: true,
              message: '请选择申请部门'
            }
          ]}
        >
          <TreeSelect
            treeData={tree.data}
            treeNodeFilterProp="title"
            showSearch
            placeholder="请选择申请部门"
            allowClear
          />
        </Form.Item>
        <Form.Item
          label="采购金额"
          name="purchaseAmount"
          rules={[
            {
              required: false,
              message: '请输入采购金额'
            }
          ]}
        >
          <Input placeholder="请输入采购金额" disabled />
        </Form.Item>
        <EditableProTable<DataSourceType>
          rowKey="key"
          headerTitle="详情"
          actionRef={actionRef}
          maxLength={5}
          // scroll={{
          //   x: 960
          // }}
          recordCreatorProps={{
            position: 'bottom',
            record: () => {
              return {
                key: Date.now()
              };
            }
          }}
          loading={false}
          toolBarRender={() => []}
          columns={columns}
          request={async () => ({
            data: [],
            total: 3,
            success: true
          })}
          value={dataSource}
          onChange={setDataSource}
          editable={{
            type: 'multiple',
            editableKeys,
            onSave: async (rowKey, data, row) => {
              // console.log(rowKey, data, row);
            },
            onChange: setEditableRowKeys
          }}
        />
      </Form>
    </Drawer>
  );
};

export default forwardRef(Edit);
